/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  RediaSearchableTableViewController.m
//  Table with search field
//
//  Created by Mads Darø Kristensen on 9/25/13.
//  Copyright (c) 2013 Redia a/s. All rights reserved.
//

#import "BASearchableTableViewController.h"
#import "BASearchableTableViewCell.h"
#import "NSArray+Selection.h"

@interface BASearchableTableViewController ()
{
    NSString* lastTypedText;
}

@property (strong, nonatomic) NSArray *currentElements;
@property (assign, nonatomic) NSInteger highlightDepth;
@property (strong, nonatomic) NSString* placeHolderText;
@property (strong, nonatomic) UIFont *font;
@property (strong, nonatomic) UIFont *highlightFont;

@end

@implementation BASearchableTableViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    self.highlightDepth = 0;
    [self.tableView registerNib:[UINib nibWithNibName:@"BASearchableTableViewCell" bundle:nil] forCellReuseIdentifier:@"BASearchableTableViewCell"];
    self.searchTextField.placeholder = self.placeHolderText;
    self.searchTextField.font = self.font;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setContents:(NSArray *)contents
{
    _contents = [contents sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    _currentElements = _contents;
    [self.tableView reloadData];
}

- (void)setPlaceHolderText:(NSString *)placeHolderText
{
    _placeHolderText = placeHolderText;
    if (self.isViewLoaded) {
        self.searchTextField.placeholder = placeHolderText;
    }
}

-(void)setFont:(UIFont *)font
{
    _font = font;
    if (self.isViewLoaded) {
        self.searchTextField.font = font;
    }
}

- (void)setHighlightFont:(UIFont *)font
{
    _highlightFont = font;
}

- (void)removeSelection
{
    if (lastTypedText.length>0 && self.searchTextField.enabled) {
        self.searchTextField.text = lastTypedText;
        [self updateSearchTerm:lastTypedText];
        [self.searchTextField becomeFirstResponder];
    } else {
        self.searchTextField.text = @"";
    }
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:NO];
}

-(void)resignFirstResponder
{
    [self.searchTextField resignFirstResponder];
}

-(void)setTextFieldEnabled:(BOOL)isEnabled
{
    self.searchTextField.enabled = isEnabled;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.currentElements count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BASearchableTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"BASearchableTableViewCell" forIndexPath:indexPath];
    
    cell.titleLabel.text = [self.currentElements objectAtIndex:indexPath.row];
    cell.highlightDepth = self.highlightDepth;
    cell.titleFont = self.font;
    cell.highlightFont = self.highlightFont;
    
    return cell;
}


#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* selectedItem = [self.currentElements objectAtIndex:indexPath.row];
    [self.searchTextField setText:selectedItem];
    if (self.delegate) {
        [self.delegate searchableTableView:self didSelectItem:selectedItem];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    DLog(@"replace %@",string);
    if ([string isEqualToString:@"\n"] || [string isEqualToString:@"\r"] || [string isEqualToString:@"\t"]) {
        return NO;
    }
    
    NSString* newstring = [self.searchTextField.text stringByReplacingCharactersInRange:range withString:string];
    
    lastTypedText = newstring;
    // This method is called whenever the user types a character in the textfield.
    
    //was (buggy?): NSString *searchTerm = [[self.searchTextField.text substringToIndex:range.location] stringByAppendingString:string];
    [self updateSearchTerm:newstring];
    
    return YES;
}

-(void)updateSearchTerm:(NSString*)searchTerm
{
    self.highlightDepth = searchTerm.length;
    self.currentElements = [self.contents arrayBySelectingElements:^BOOL(NSString *obj) {
        return (searchTerm.length <= obj.length && [searchTerm caseInsensitiveCompare:[obj substringToIndex:[searchTerm length]]] == NSOrderedSame);
    }];
    [self.tableView reloadData];
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchableTableViewDidBeginEditing:)]) {
        [self.delegate searchableTableViewDidBeginEditing:self];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchableTableViewDidEndEditing:)]) {
        [self.delegate searchableTableViewDidEndEditing:self];
    }
}

@end
